<template>
  <div id="market">
    <!-- 顶部导航栏 -->
    <van-nav-bar class="navbar" @click-left="onClickLeft">
      <template #left>
        <van-icon class="nav" name="arrow-left" />
      </template>
      <template #title>
        <div class="nav">二手市场类任务发布</div>
      </template>
    </van-nav-bar>
    <!-- 发布的内容 -->
    <van-form @submit="onSubmit">
      <!-- 物品名称 -->
      <van-field
        v-model="goodsName"
        name="物品名称"
        label="物品名称"
        placeholder="物品名称"
        :rules="[{ required: true, message: '请填写物品名称' }]"
      />
      <!-- 详情介绍 -->
      <textarea class="textarea" v-model.lazy="taskDetails" placeholder="请输入详细描述内容"></textarea>
      <!-- 详情附带的图片文件 -->
      <van-field name="uploader" label="图片上传">
        <template #input>
          <van-uploader v-model="uploader"  :after-read="afterRead" :before-delete="beforeDelete"/>
        </template>
      </van-field>
      <!-- 选择有效时长 -->
      <van-field
        readonly
        clickable
        name="datetimePicker"
        label="到期时间"
        :value="checkTime"
        placeholder="点击选择时间"
        @click="showPicker = true"
        :rules="[{ required: true, message: '请填写到期时间' }]"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-datetime-picker
          type="datetime"
          title="选择到期时间"
          @confirm="onConfirm"
          @cancel="showPicker = false"
          v-model="time"
          :formatter="formatter"
          :min-date="minDate"

        />
      </van-popup>
      <!-- 悬赏金额 -->
      <van-field
        label="悬赏金额"
        type="number"
        v-model="money"
        name="money"
        placeholder="请输入有效金额"
        :rules="[{ required: true, message: '请输入金额' }]"
      />
      <!-- 发布按钮 -->
      <div class="submit">
        <van-button round block type="info" native-type="submit">
          发布
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';
export default {
  name: 'PublishMarket',
  data () {
    return {
      goodsName: '',
      taskDetails: '',
      uploader: [],
      minDate: new Date(),
      time: new Date(),
      checkTime: '',
      showPicker: false,
      money: null,
      fileNameCount:[]
    }
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      } else if (type === 'day') {
        return `${val}日`;
      } else if (type === 'hour') {
        return `${val}时`;
      } else if (type === 'minute') {
        return `${val}分`;
      }
    },
    onConfirm(value) {
      let year = value.getFullYear();
      let m = value.getMonth() + 1; // 解决月份总是比选择的月份少一的问题
      let month = m > 9 ? m : '0' + m;
      let day = value.getDate() > 9 ? value.getDate() : '0' + value.getDate();
      let hours = value.getHours() > 9? value.getHours() : '0' + value.getHours();
      let minutes = value.getMinutes() > 9? value.getMinutes() : '0' + value.getMinutes();
      this.checkTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + '00'
      this.showPicker = false;
    },
    onSubmit() {
      console.log("点击了发布任务")
      var fileName = {};
      for(var i in this.fileNameCount){
          fileName[i]=this.fileNameCount[i];
          console.log(fileName);
      }
      fileName = JSON.stringify(fileName);
      console.log(fileName);
      console.log(this.goodsName);
      let params = new URLSearchParams();
      params.append('img',fileName);
      params.append('classify',"4");
      params.append('title',this.goodsName);
      params.append('mycontent',this.taskDetails);
      params.append('money',this.money);
      params.append('time',this.checkTime);
      console.log(this.checkTime)
      this.axios({
          method: "post",
          url: this.$store.state.url+"/order",
          headers:{
           'Authorization': localStorage.token,
                },
          params,
      }).then((res) => {
        this.$router.push('/');
        console.log(res.data);
      }).catch((err) => {
          console.log(err);
      })
    },
     afterRead(file) {
      // 此时可以自行将文件上传至服务器
      var formData = new FormData();
      formData.append('file',file.file);
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      this.axios({
          method: "post",
          url: this.$store.state.url+"/picture",
          headers:{
           "Content-Type": "multipart/form-data",
           'Authorization': localStorage.token,
                },
          data:formData,
      }).then((res) => {
        console.log(res.data);
        Toast.success('上传成功');
        Toast.clear();
        this.fileNameCount.push(res.data.data.file_name);
        console.log(this.fileNameCount);
      }).catch((err) => {
          console.log(err);
      })
    },
    beforeDelete(file){
        console.log(file)
        for(var t in this.uploader){
          if(file.file ==this.uploader[t].file){
                console.log(t);
                if(this.fileNameCount[t]){
                this.fileNameCount.splice(t,1);
                console.log(this.fileNameCount);
                }
                return true;
          }
        }
        // return true;
    }
  }
}
</script>

<style scoped>
  .navbar {
    background: linear-gradient(-45deg, #0066ff, #4f64ff, #7053ff, #3321fb);
    box-shadow: 0 2px 5px #cccccc;
    color: #ffffff;
  }
  .nav {
    color: #fff;
    font-size: 20px
  }
  .textarea {
    width: 100%;
    height: 100px;
    box-sizing: border-box;
    margin: 30px 0 0 0;
    padding: 10px;
    resize: none;
    border: 0;
  }
  .submit {
    margin: 16px
  }
</style>